package com.essc.controller;

import com.essc.service.UserService;
import com.essc.utils.JsonResult;
import com.essc.utils.LoginResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@CrossOrigin
@RequestMapping("/upload")
@RestController
public class UploadController {
    @Autowired
    UserService userService;
//    //    处理头像上传
//    @RequestMapping("/upload")
//    @ResponseBody
//    public JsonResult uploadAvatar(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "username") String username, HttpSession session) throws FileNotFoundException {
//        return userService.uploadAvatar(file, username, session);
//    }
//    @PostMapping("/avatar")
//    public LoginResult uploadGoodImg(@RequestParam(value="file") MultipartFile file) throws FileNotFoundException {
//        System.out.println("接收到了图片上传请求");
//        String fileName = file.getOriginalFilename(); //原文件名
//        String path = ResourceUtils.getURL("classpath:").getPath()+"static/avatar/";//static存储路径
//        String key = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date().getTime());//时间戳命名文件
//        String fullPath = path + key + "-" + fileName; //拼接文件名
//        System.out.println("存储路径："+fullPath);
//        File dest = new File(fullPath);
//        try {
//            file.transferTo(dest);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        String url = "http://localhost:8080/avatar/"+key + "-" + fileName;//图片地址
//        return LoginResult.success(url);
//    }

    @PostMapping("/good")
    public LoginResult uploadAvatar(@RequestParam(value="file") MultipartFile file) throws FileNotFoundException {
        String fileName = file.getOriginalFilename(); //原文件名
        String path = ResourceUtils.getURL("classpath:").getPath()+"static/img/";//static存储路径
        String key = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date().getTime());//时间戳命名文件
        String fullPath = path + key + "-" + fileName; //拼接文件名
        System.out.println("存储路径："+fullPath);
        File dest = new File(fullPath);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = "http://localhost:8080/img/"+key + "-" + fileName;//图片地址
        return LoginResult.success(url);
    }
}
